﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using PostSharp.Laos;

namespace PostSharpModel.Cache
{
    [Serializable]
    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class CacheAttribute : OnMethodBoundaryAspect
    {

        private static readonly Dictionary<string, object> cache = new Dictionary<string, object>();

        /// <summary>
        /// 当进入某个方法之前执行
        /// </summary>
        /// <param name="eventArgs"></param>
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
            //发方法名为缓存的key
            string key = eventArgs.Method.Name;
            
            lock (cache)
            {
                object value;
                
                //是否存在缓存值，如果存在就不执行方法体，否则就设置缓存
                if (!cache.TryGetValue(key, out value))
                {
                    eventArgs.MethodExecutionTag = key;
                    //下面执行方法体内容
                }
                else
                {
                    eventArgs.ReturnValue = cache[key];
                    eventArgs.FlowBehavior = FlowBehavior.Return;
                }
            }
        }

        /// <summary>
        /// 当方法成功完成时执行
        /// </summary>
        /// <param name="eventArgs"></param>
        public override void OnSuccess(MethodExecutionEventArgs eventArgs)
        {
            //取缓存 key
            string key = eventArgs.MethodExecutionTag as string;

            //设置缓存 key 对应的值
            lock (cache)
            {
                cache[key] = eventArgs.ReturnValue;
            }
        }
    }
}
